<?php

/**
 * @Author: 杰少Pakey
 * @Email : admin@ptcms.com
 * @File  : public.php
 */
class PublicController extends CommonController
{
	public function init()
	{
		parent::init();
		$comeurl = isset($_REQUEST['comeurl']) ? $_REQUEST['comeurl'] : ((empty($_SERVER['HTTP_REFERER']) || stripos($_SERVER['HTTP_REFERER'],'login')!==false || stripos($_SERVER['HTTP_REFERER'],'register')!==false ) ? U('user.index.index'): $_SERVER['HTTP_REFERER']);
		if (strpos($comeurl, 'login') !== false || strpos($comeurl, 'register') !== false) {
			$comeurl = I('cookie.comeurl', 'str', PT_DIR . '/');
		} else {
			cookie('comeurl', $comeurl, 600);
		}
		$this->comeurl = $comeurl;
		C('layout',false);//关闭layout
	}

	public function loginAction()
	{
		if (IS_LOGIN) {
			//已登录用户直接跳走
			$this->redirect($this->comeurl);
		}elseif (IS_POST) {
			$where = array();
			if (strpos($_POST['email'], '@')) {
				$email = I('post.email', 'email', '');
				if ($email) $where['email'] = $email;
			} else {
				$username = I('post.email', 'username', '');
				if ($username) $where['username'] = $username;
			}
			if (empty($where)) {
				$this->error('您的邮箱或者帐号输入有误');
			}
			if (M('user')->login($where, $_POST['password'])) {
				$this->success('登录成功', $this->comeurl);
			} else {
				$this->error('您的帐号或者密码有误！');
			}
		}else{
			$this->assign('email',I('cookie.email',null,''));
			$this->display();
		}
	}

	public function registerAction()
	{
		if (IS_LOGIN) {
			//已登录用户直接跳走
			$this->redirect($this->comeurl);
		}elseif (IS_POST) {
			$param['email'] = I('post.email', 'email', '');
			$param['username'] = I('post.username', 'username', '');
			$param['password'] = md5($_POST['password']);
			if (empty($param['email'])){
				$this->error('请输入正确格式的邮箱');
			} elseif(M('user')->where(array('email'=>$param['email']))->find()) {
				$this->error('您输入的邮箱已经被使用');
			}
			if (empty($param['username'])){
				$this->error('请输入正确格式的用户名（3-15位字符、数字、中文）');
			} elseif(M('user')->where(array('username'=>$param['username']))->find()) {
				$this->error('您输入的用户名已经被使用');
			}
			if (M('user')->reg($param)){
				$this->success('注册成功！',$this->comeurl);
			}else{
				$this->error('注册失败');
			}
		}else{
			$this->display();
		}
	}

    public function thirdloginAction()
    {
        $type=I('get.type','str','');
        $type=in_array($type,array('qq','weibo'))?$type:'qq';
        $callback=PT_URL.U('user.public.thirdlogin',array('type'=>$type));
        if (empty($_GET['code'])){
            //没有code参数 则去第三方登录
            $url = oauth::getInstance($type)->authorize($callback);
            $this->redirect($url);
        }else{
            // 有第三方code 先判断是否绑定了 没有绑定进行绑定流程
            $code=I('get.code','str','');
            $token=oauth::getInstance($type)->getAccessToken($code,$callback);
            if (!is_array($token)) $this->error($token,U('user.public.login'));
            if ($info=M('user')->checkopenid($token['openid'],$type)){
                M('user')->setLoginStatus($info);
                $this->success('登陆成功！',$this->comeurl);
            }else{
                $this->openid=$token['openid'];
                $this->thirdtype=$type;
                $this->assign('email',I('cookie.email',null,''));
                $this->display();
            }
        }
    }

    public function thirdlogincheckAction()
    {
        if (IS_POST){
            $openid = I('post.openid','str','');
            $type = I('post.thirdtype','str','');
            $thirdtype = $type.'id';

            $bind_email = $_POST['bind_email'];
            $bind_password = $_POST['bind_password'];

            $new_username = $_POST['new_username'];
            $new_email = $_POST['new_email'];
            $new_password = $_POST['new_username'];


            //绑定已有账号
            if($bind_email && $bind_password){
                $where = array();
                if (strpos($bind_email, '@')) {
                    $email = I('post.bind_email', 'email', '');
                    if ($email) $where['email'] = $email;
                } else {
                    $username = I('post.email', 'username', '');
                    if ($username) $where['username'] = $username;
                }
                if (empty($where)) {
                    $data =  array('status'=>0,'info'=>'您的邮箱或者帐号输入有误');
                    $this->ajax($data);
                }
                if (M('user')->login($where, $bind_password)) {
                    M('user')->where($where)->update(array($thirdtype=>$openid));
                    //绑定成功
                    $data =  array('status'=>1,'info'=>'绑定老帐号成功！','url'=>$this->comeurl);
                    $this->ajax($data);
                } else {
                    $data =  array('status'=>0,'info'=>'您的帐号或者密码有误！');
                    $this->ajax($data);
                }
            }else if($new_username && $new_email && $new_password){
                $param['email'] = I('post.new_email', 'email', '');
                $param['username'] = I('post.new_username', 'username', '');
                $param['password'] = md5($new_password);
                if (empty($param['email'])){
                    $data =  array('status'=>0,'info'=>'请输入正确格式的邮箱');
                    $this->ajax($data);
                } elseif(M('user')->where(array('email'=>$param['email']))->find()) {
                    $data =  array('status'=>0,'info'=>'您输入的邮箱已经被使用');
                    $this->ajax($data);
                }
                if (empty($param['username'])){
                    $data =  array('status'=>0,'info'=>'请输入正确格式的用户名（3-15位字符、数字、中文）');
                    $this->ajax($data);
                } elseif(M('user')->where(array('username'=>$param['username']))->find()) {
                    $data =  array('status'=>0,'info'=>'您输入的用户名已经被使用');
                    $this->ajax($data);
                }
                if (M('user')->reg($param)){
                    M('user')->where(array('email'=>$param['email']))->update(array($thirdtype=>$openid));
                    //注册绑定成功
                    $data =  array('status'=>1,'info'=>'绑定新帐号成功！','url'=>$this->comeurl);
                    $this->ajax($data);
                }else{
                    $data =  array('status'=>0,'info'=>'注册失败');
                    $this->ajax($data);
                }
            }else{
                $data =  array('status'=>0,'info'=>'您输入的参数有误');
                $this->ajax($data);
            }
            $this->ajax($data);
        }
    }

	public function thirdlogin1Action()
	{
		$this->assign('email',I('cookie.email',null,''));
		$data =  array('status'=>0,'info'=>'');
		$openid = isset($_POST['openid'])?$_POST['openid']:$_GET['openid'];
		$thirdtype = isset($_POST['thirdtype'])?$_POST['thirdtype']:$_GET['thirdtype'];
		$this->assign('openid',$openid);
		$this->assign('thirdtype',$thirdtype);
		$thirdtype .= 'id';
		
		
		//检测openid是否被绑定
		if($checkInfo = $this->checkOpenid($openid,$thirdtype)){
			if(IS_POST || IS_LOGIN){
				$this->error('已经绑定了账号!',U('user.profiles.bind'));
			}else{
				M('user')->setLoginStatus($checkInfo);
				$this->success('登陆成功！',U('user.index.index'));
			}
			
		}

		if(IS_LOGIN && !IS_POST){
			M('user')->where(array('email'=>$this->userinfo['email']))->update(array($thirdtype=>$openid));
			
			// echo M('user')->getLastSql();
			 // exit;
			//绑定成功
			// $data =  array('status'=>1,'info'=>'绑定成功！','url'=>U('user.profiles.bind'));
			// $this->ajax($data);
			$this->success('绑定成功！',U('user.profiles.bind'));
		}else{
			if(IS_POST){

			}
		}
		$this->display();
	}

	public function logoutAction()
	{
		M('user')->delLoginStatus();
		$this->redirect($this->comeurl);
	}
}